package com.ang.demo;

import com.ang.future.config.MyThreadFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

/**
 * @author ssang
 * @date 2023-03-17 14:30
 */
public class CountDownLatchTest {

    private AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) {
        CountDownLatchTest test = new CountDownLatchTest();

        test.test01();
    }

    public void test01(){
        //构建List
        List<Integer> list = new ArrayList();
        IntStream.range(0,10000).forEach(i->{
            list.add(i);
        });

        //线程池
        ExecutorService myExecutor = new ThreadPoolExecutor(2, 10,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(10),//阻塞队列，保存操作请求线程
                new MyThreadFactory(),//创建线程的工厂类
                new ThreadPoolExecutor.CallerRunsPolicy());

        //
        CountDownLatch countDownLatch = new CountDownLatch(list.size());

        System.out.println("任务开始-------------------------------->");
        for (Integer i : list) {
//            System.out.println("分配任务："+i);
            CompletableFuture.runAsync(doSomethingRunnable(i,countDownLatch), myExecutor);
        }

        myExecutor.shutdown();

        try {
            //等待任务完成
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //如果没有countDownLatch.await();for循环结束，立马打印
        System.out.println("任务结束-------------------------------->，处理任务数："+count.get());
    }


    public Runnable doSomethingRunnable(Integer flag, CountDownLatch countDownLatch){
        return ()->{
            this.doSomething(flag, countDownLatch);
        };
    }

    //使用synchronized，保证当前方法的原子性
    public synchronized void doSomething(Integer flag, CountDownLatch countDownLatch){
        try{
            Thread.sleep(1);
            System.out.println("----------->"+Thread.currentThread().getName()+"    :当前处理任务："+flag);
            count.incrementAndGet();
        }catch (Exception e){
            System.out.println("----------->失败任务："+flag);
        }finally {
            //
            countDownLatch.countDown();
        }
    }
}
